<template>
  <div>
    <p>{{ vTitle }}</p>

    <div class="my-3 text-primary">
      <p>{{ append }}</p>
    </div>

    <div class="flex-center">
      <el-input v-model="todo" type="text" class="form-control" />
      <el-button type="primary" @click="add">Add</el-button>
    </div>
    <p>[TodoLength: {{ todoLength }}, 数量: {{ itemsQuantity }}]</p>

    <div class="list-group">
      <div
        class="flex-center"
        v-for="(item,index) in items"
        :key="index"
      >
        <span class="card-style">{{ item }}</span>
        <button class="close" @click="remove(index)">
          <span>&times;</span>
        </button>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, reactive, computed, watch, onBeforeMount, onMounted } from 'vue'

function useTitle (props) {
  const vTitle = computed(() => '-' + props.title + '-')

  return {
    vTitle
  }
}

function useTodoLength (todo) {
  const todoLength = ref(0)

  watch(
    // getter
    () => todo.value.length,
    // callback
    (length) => {
      todoLength.value = length
    },
    // watch Options
    {
      immediate: true
    }
  )

  return {
    todoLength
  }
}

function useItems (todo) {
  const items = reactive(['A', 'B'])
  console.log('item', items)
  const itemsQuantity = computed(() => items.length)
  const append = ref('')

  watch(
    // getter
    () => items,
    // callback
    (items) => {
      append.value = ''
      items.forEach(item => {
        append.value += item + ' '
      })
    },
    // watch Options
    {
      immediate: true,
      deep: true
    }
  )

  const add = () => {
    if (todo.value) {
      items.push(todo.value)
      todo.value = ''
    }
  }

  const remove = index => {
    items.splice(index, 1)
  }

  return {
    items,
    itemsQuantity,
    append,
    add,
    remove
  }
}

export default {
  props: {
    title: String,
    initInput: String
  },
  setup (props) {
    const todo = ref(props.initInput)

    onBeforeMount(() => {
      console.log('V3 beforeMount!')
    })

    onMounted(() => {
      console.log('V3 mounted!')
    })

    return {
      todo,
      ...useTitle(props),
      ...useTodoLength(todo),
      ...useItems(todo)
    }
  },
  mounted () {
    console.log('V3V2 mounted!')
  }
}
</script>

<style lang="less">
@import '~@/common/less/normal.less';
</style>
